<?php

namespace App\Containers\AppSection\Accreditation\Actions;

use App\Containers\AppSection\Accreditation\Models\Accreditation;
use App\Containers\AppSection\Accreditation\Tasks\CreateRemarkTask;
use App\Containers\AppSection\Accreditation\Tasks\FindAccreditationByIdTask;
use App\Containers\AppSection\Accreditation\Tasks\SendToAccreditationTask;
use App\Containers\AppSection\Log\Tasks\CreateLogTask;
use App\Containers\AppSection\Profile\Tasks\UpdateProfileTask;
use App\Ship\Parents\Actions\Action;
use App\Ship\Parents\Requests\Request;

class UpdateAccreditationAction extends Action
{
    public function run($id, Request $request): Accreditation
    {
        $accreditation = app(FindAccreditationByIdTask::class)->run($id);

        if ($request->getInputByKey('type') === 'accreditation_checking') {
            $accreditation = app(SendToAccreditationTask::class)->run([
                'profile_id' => $accreditation->profile->id,
                'stage' => 'moderator'
            ]);

            app(UpdateProfileTask::class)->run($accreditation->profile->id, [
                'accreditation_status_key' => $request->getInputByKey('type'),
                'accredited_at' => null,
                'accreditation_id' => $accreditation->id
            ]);
        }

        if (!empty($request->getInputByKey('remarks'))) {
            foreach ($request->getInputByKey('remarks') as $remark) {
                app(CreateRemarkTask::class)->run([
                    'message' => $remark,
                    'accreditation_id' => $accreditation->id,
                    'profile_id' => $request->profile()->id
                ]);
            }
        }

        $log = '';
        switch ($request->getInputByKey('type')) {
            case 'accreditation_checking':
                $log = "Профиль №{$accreditation->profile->id} отправлен на повторную аккредитацию.";
                break;
        }


        app(CreateLogTask::class)->run($accreditation->profile->id, $log, 'accreditation', $accreditation->id);
        app(CreateLogTask::class)->run($request->profile()->id, $log, 'accreditation', $accreditation->id);

        return $accreditation;
    }
}
